<template>
  <div>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      :size="formSize"
      status-icon
    >
      <el-form-item label="任务类型" prop="taskType">
        <el-select v-model="ruleForm.taskType" placeholder="请选择任务类型">
          <el-option
            v-for="item in taskTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务URL" prop="taskUrl">
        <el-input v-model="ruleForm.taskUrl" placeholder="请输入任务地址" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { createTask, taskType } from "@/api/createTask";
import { ElMessage } from "element-plus";

// 表单数据类型
interface RuleForm {
  taskUrl: string;
  taskType: string;
}

const formSize = ref<ComponentSize>("default");
// 表单实例
const ruleFormRef = ref<FormInstance>();
// 表单数据
const ruleForm = reactive<RuleForm>({
  taskUrl: "",
  taskType: "",
});

// 任务类型下拉值
const taskTypeOptions = ref();

// 菜单校验规则
const rules = reactive<FormRules<RuleForm>>({
  taskUrl: [{ required: true, message: "请输入任务地址", trigger: "blur" }],
  taskType: [{ required: true, message: "请选择任务类型", trigger: "blur" }],
});

// 点击提交表单时
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const getList = {
        taskType: ruleForm.taskType,
        taskUrl: ruleForm.taskUrl,
      };
      createTask(getList)
        .then((res) => {
          ElMessage.success("提交成功");
        })
        .catch((err) => {
          ElMessage.error(err.message);
        });
    } else {
      ElMessage.warning("还有必填项为填！");
    }
  });
};

// 获取任务类型
const taskTypeFn = () => {
  taskType().then((res) => {
    const options = res.data.map((item: any) => {
      return {
        label: item,
        value: item,
      };
    });
    taskTypeOptions.value = options;
  });
};

onMounted(() => {
  taskTypeFn();
});
</script>

<style scoped></style>
